<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Observer(data) {
            this.data = data;
            this.walk(data);
        }
        let p = Observer.prototype;
        p.list = {};
        p.walk = function (obj) {
            let val;
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    val = obj[key];
                    if (typeof val === 'object') {

                        new Observer(val);
                    }
                    this.conver(key, val)
                }
            }
        };
        p.conver = function (key, val) {
            Object.defineProperty(this.data, key, {
                enumerable: true,
                configurable: true,
                get: function () {
                    console.log('你访问了' + key);
                    return val
                },
                set: function (newval) {
                    console.log('你设置了' + key)
                    console.log('新的' + key + '为' + newval);
                    p.trigger(key,newval);
                    if (newval === val) return;
                    val = newval;
                }
            })
        };
        p.$watch = function (key, fn) {
            if (!this.list[key]) {
                this.list[key] = [];
            }
            this.list[key].push(fn);
        };
        p.trigger = function () {
            var key = Array.prototype.shift.call(arguments);
                fns = this.list[key];
            if (!fns || fns.length === 0) {
                return false;
            };
            for (var i = 0, fn; fn = fns[i++];) {
                fn.call(this, arguments[0])
            }
        };
        let data = {
            name: 'youngwind',
            age: 25
        };

        let app = new Observer(data);
        // p.$watch('age', function (age) {
        //     console.log('我的年纪变了，现在已经是：'+age+'岁了')
        // })
        console.log(app)
    </script>
</body>

</html>